package com.wm.task.Task2.manageFile;

import com.wm.task.Task2.vo.Contacts;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ManageFile {
    //D:\java\study\test\contacts
    private final String PATH = "D:/java/study/test/contacts/contacts";


    public void writeFile(List<Contacts> contacts) {

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH))) {
            for (int i = 0; i < contacts.size(); i++) {
                oos.writeObject(contacts.get(i));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Contacts> readFile() {
        List<Contacts> contacts = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PATH))) {
            while (true) {
                try {
                    Contacts contact = (Contacts) ois.readObject();
                    contacts.add(contact);
                } catch (EOFException e) {
                    break;
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return contacts;
    }

}
